<template>
  <el-col :span="14" class="left-container" :style="themeOpacity">
    <a-spin :spinning="spinning" tip="初始化桌面..." style="width: 100%;height: 100%;">
      <div class="tab-content" style="padding-left: 3px;">
        <el-tag
          v-for="(tag, index) in deskTopList"
          :key="tag.desktopName + index"
          :closable="setting"
          class="desktop-tabs"
          :class="index === curDeskTop ? 'theme-less-background-color' : ''"
          size="normal"
          :style="themeOpacity"
          :disable-transitions="true"
          @close="removeTab(index)"
          @click="changeTag(tag, index)"
        >
          {{ tag.desktopName }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="addTagInput"
          v-model="addTag"
          ref="saveTagInput"
          size="normal"
          style="width: 80px;"
          @keyup.enter.native="addTagConfirm"
          @blur="addTagConfirm"
        >
        </el-input>
        <el-button
          v-else
          class="el-icon-plus"
          size="large"
          :style="{
            ...themeOpacity,
            verticalAlign: 'top',
            height: '40px'
          }"
          @click="addTabClick"
        ></el-button>
        <el-button
          class="el-icon-setting"
          size="large"
          :style="{
            ...themeOpacity,
            marginLeft: '0',
            verticalAlign: 'top',
            height: '40px'
          }"
          v-show="!setting"
          @click="changeDraggable"
        ><span style="margin-left: 5px;">编辑桌面</span></el-button
        >
        <el-button
          class="el-icon-success"
          size="large"
          type="danger"
          :style="{
            marginLeft: '0',
            verticalAlign: 'top',
            height: '40px'
          }"
          v-show="setting"
          @click="addCardItem"
        ><span style="margin-left: 5px;">新增文件夹</span></el-button
        >
        <el-button
          class="el-icon-success"
          size="large"
          type="primary"
          :style="{
            marginLeft: '0',
            verticalAlign: 'top',
            height: '40px'
          }"
          v-show="setting"
          @click="saveSetting"
        ><span style="margin-left: 5px;">保存设置</span></el-button
        >
      </div>
      <div class="card-content scrollbar-none-horizontal">
        <el-scrollbar style="height: 100%;">
          <el-row :gutter="24" style="min-height: 300px;">
            <draggable
              v-model="layout"
              style="width: 100%;min-height: 300px;"
              group="group"
              v-bind="dragOptions"
              :move="canCardMove"
              :disabled="!setting"
              @start="cardDraggable = true"
              @end="cardDraggable = false"
            >
              <el-col
                :span="12"
                style="padding: 0px 6px 0px 15px;margin-top: 10px;"
                v-for="(item, index) in layout"
                :key="'draggable' + index"
              >
                <!--<components :is="item.components" :ref="item.components" :isDraggable="setting" />-->
                <DynamicRender @delAction="delCard" :desktopId="deskTopId" :dataSource="item" :setting="setting"/>
              </el-col>
            </draggable>
            <a-empty v-show="!layout.length && !setting" :image="emptySrc" description="暂无桌面信息" class="empty-style"/>
          </el-row>
        </el-scrollbar>
      </div>
    </a-spin>
  </el-col>
</template>

<script>
  import { desktopList, desktopDetails, desktopAdd, desktopEdit, addFolder, deleteDeskTop } from '@client/addHome/service'
  import Empty from 'ant-design-vue/es/empty'
  import DynamicRender from './components/DynamicRender'
  import {
    getDraggableName,
    getDraggableTargetName
  } from '@/utils/draggableHelper'

  export default {
    name: 'DesktopContainer',
    data() {
      const emptySrc = Empty.PRESENTED_IMAGE_SIMPLE
      return {
        curDeskTop: 0,
        spinning: false,
        closeTab: false,
        // 桌面list
        deskTopList: [],
        emptySrc,
        addTag: '',
        addTagInput: false,
        cardDraggable: false, // 卡片是否在拖动
        setting: false, // 是否能够拖拽
        layout: [],
        applicationChild: [], // 当前显示的可用应用列表
        applicationCurIndex: 0, // 当前显示的可用应用索引
        // 可拖拽到可用卡片的组件名称
        canDraggableNames: ['TeacherSalary', 'CardConsumption', 'BookList']
      }
    },
    props: {
      dragOptions: {
        type: Object,
        default: () => {
        }
      },
      themeOpacity: {
        type: Object,
        default: () => {
        }
      }
    },
    computed: {
      deskTopId() {
        return this.deskTopList[this.curDeskTop]['desktopId'] || -1
      },
      resource() {
        //获取新增的app
        const draggableObj = this.$store.state.app.draggableObj
        let source = this.layout;
        if (draggableObj && source.length) {
          let findFlags = []
          // 查找相同项
          source.map((item, index) => {
            let isContains =
              item['folderType'] === draggableObj['folderType'] &&
              item['cardId'] === draggableObj['cardId']
            if (isContains)
              findFlags.push({
                ...item,
                findIndex: index
              })
          })
          // 含有两个条目以上，重复拖拽需要去重
          if (findFlags.length && findFlags.length > 1) {
            // 保留第一个
            findFlags.splice(0, 1)
            // 清除所有冗余元素
            findFlags.map(flagItem => source.splice(flagItem.findIndex, 1))
          }
        }
        return source
      }
    },
    methods: {
      // 删除卡片
      delCard(delItem) {
        if (Object.getOwnPropertyNames(delItem).length) {
          const index = this.layout.length && this.layout.findIndex((item) => delItem.folderId === item.folderId);
          console.log(index)
          if (typeof index === 'number' && index !== -1) {
            this.layout.splice(index, 1)
          }
        }
      },
      canCardMove(e, originalEvent) {
        // 卡片移入进来
        // 获取移动的卡片名称
        const cardTagret = getDraggableName(e)
        // 是否为可用卡片的数据项
        const condition = name => name.toLocaleUpperCase() === cardTagret.toLocaleUpperCase()
        const isCanDraggedCard = this.canDraggableNames.findIndex(condition) !== -1
        // 是否拖到可用卡片容器
        const isDraggedUseCard = getDraggableTargetName(e) === 'canUseCard'
        // 目标不是可用卡片容器不需要阻止
        // return isDraggedUseCard ? isDraggedUseCard && isCanDraggedCard : true
        // 暂时不能回收
        return isDraggedUseCard ? !isDraggedUseCard && isCanDraggedCard : true
      },
      addCardItem() {
        // 新增收纳柜
        this.layout.unshift({
          folderName: '标题',
          folderType: 3,
          isNewFolder: true,
          desktopId: this.deskTopId,
          receptionFolderApplyList: []
        })
      },
      saveSetting() {
        // 保存设置
        const loading = this.$loading({
          lock: true,
          text: '保存设置...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const params = {
          desktopId: this.deskTopId,
          sysReceptionFolderList: this.layout
        }
        addFolder(params)
          .then(res => {
            if (res.code !== 200) return this.$message.error(res.msg || '新增失败')
            this.setting = false
            this.init()
          })
          .finally(() => {
            loading.close()
          })
      },
      // 点击设置按钮
      changeDraggable() {
        this.setting = !this.setting
      },
      // 删除卡片
      cardClose(index) {
      },
      async changName(value, index) {
        const result = await this.$httpHandler(desktopEdit, Object.assign(this.deskTopList[index], {desktopName: value}))
        if (!result) return this.$message.error('修改失败')
        this.deskTopList[index].desktopName = value
      },
      // 切换桌面
      async changeTag(tag, index) {
        if (this.setting) {
          // 修改昵称
          this.$prompt('桌面名称', '修改名称', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValue: this.deskTopList[index].desktopName,
            inputPattern: /\S+/,
            inputErrorMessage: '桌面名称不能为空'
          }).then(({ value }) => {
            this.changName(value, index)
          })
        } else {
          this.curDeskTop = index
          this.init()
        }
      },
      // 添加桌面
      addTagConfirm() {
        let addTag = this.addTag.trim()
        if (addTag) {
          this.$httpHandler(desktopAdd, {
            desktopName: addTag
          }).then(() => {
            this.init()
          })
        }
        this.addTagInput = false
        this.addTag = ''
      },
      addTabClick() {
        this.addTagInput = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.focus()
        })
      },
      async removeTab(index) {
        if (this.deskTopList.length === 1) return this.$message.warning('需至少保留一个桌面')
        const result = await this.$httpHandler(deleteDeskTop, this.deskTopList[index].desktopId)
        if (!result) return this.$message.error('删除失败')
        if (index === this.curDeskTop) {
          // 删除当前桌面
          this.layout = []
          this.curDeskTop = 0
        }
        // 如果删除前面的
        if (index < this.curDeskTop) {
          // 索引减1
          this.curDeskTop = this.curDeskTop - 1
        }
        this.deskTopList.splice(index, 1)
        console.log(index)
      },
      getDesktopDetails(id) {
        this.spinning = true
        this.$httpResultHandler(desktopDetails, id).then(res => {
          this.spinning = false
          this.layout = res.data || []
        })
      },
      async init() {
        const desktopInfo = await this.$httpResultHandler(desktopList)
        this.deskTopList = desktopInfo.data || []
        desktopInfo &&
        desktopInfo.data &&
        desktopInfo.data.length &&
        this.getDesktopDetails(desktopInfo.data[this.curDeskTop].desktopId)
      }
    },
    watch: {
      setting: {
        handler(val) {
          this.$emit('openSetting', val)
        },
        immediate: true
      },
      resource () {}
    },
    components: {
      DynamicRender
    },
    mounted() {
      this.init()
    }
  }
</script>

<style lang="scss" scoped>
  .left-container {
    background-color: #fff;
    padding: 10px 10px 20px 10px;
    display: table-cell;
    top: 0;
    bottom: 0;

    .tab-content {
      .desktop-tabs {
        display: inline-block;
        height: 40px;
        min-width: 80px;
        line-height: 40px;
        border-radius: 0px;
        text-align: center;
        border-color: #ddd;
        background-color: #fff;
        cursor: pointer;
        color: #222;

        &.active {
          ::v-deep .el-icon-close {
            color: #fff;
          }
        }

        ::v-deep .el-icon-close {
          color: #222;

          &:hover {
            color: #fff;
          }
        }
      }
    }

    .card-content {
      height: 800px;
      max-height: 800px;

      .vue-grid-item {
        height: 275px;
        position: relative;
        // margin-top: 15px;
        .card-close {
          display: inline-block;
          position: absolute;
          top: -4px;
          right: 4px;
          background-color: #ccc;
          border-radius: 50%;
          width: 16px;
          height: 16px;
          text-align: center;
          line-height: 16px;
          font-size: 12px;
          color: #fff;
        }

        ::v-deep .el-card__body {
          height: calc(100% - 40px);
          box-sizing: border-box;
        }

        .el-card {
          ::v-deep .el-card__header {
            height: 40px;
            line-height: 40px;
            background-color: #f3f5f7;
            font-size: 14px;
            padding: 0px 20px;

            .clearfix > span {
              width: 70px;
              height: 17px;
              font-size: 16px;
              font-family: PingFang SC;
              font-weight: 500;
              color: #333333;
            }
          }
        }
      }
    }
  }

  .card-content {
    ::v-deep .el-card__header {
      background-color: rgba(244, 244, 244, 0.8);
      box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.1);
    }

    ::v-deep .el-card__body {
      height: 230px;
      max-height: 230px;
    }
  }

  .empty-style {
    padding-top: 50px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 0px;
  }
</style>
